package com.lanou3g.hw0414;

import com.sun.tools.doclets.internal.toolkit.util.DocFinder;

import java.io.*;
import java.util.ArrayList;

/**
 * Created by dllo on 18/4/16.
 */
// 存储用户信息
//user要存储的用户信息
public class IOUtils {
    public static final String FILE_NAME = "user.txt";

    public static void saveUser(User user) {
        File file = new File(FILE_NAME);
        OutputStream os = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            os = new FileOutputStream(file,true);
            String userInfo = user.getUsername() + ":" + user.getPwd() + ";";
            os.write(userInfo.getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(os);
        }
    }

    public static ArrayList<User> initUsers() {
        ArrayList<User> users = new ArrayList<>();
        File file = new File(FILE_NAME);
        if (!file.exists()) {
            return users;
        }
        InputStream is = null;

        try {
            is = new FileInputStream(file);
            byte[] buff = new byte[1024];
            int pos = 0;
            StringBuilder builder = new StringBuilder();
            while ((pos = is.read(buff)) != -1) {
                String s = new String(buff, 0, pos);
                builder.append(s);
            }
            String data = builder.toString();

            String[] userInfos = data.split(";");
            for (String userInfo : userInfos) {
                String[] info = userInfo.split(":");
                User user = new User();
                user.setUsername(info[0]);
                user.setPwd(info[1]);
                users.add(user);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(is);
        }

        return users;
    }

    public static void closeAll(Closeable... closeables) {
        if (closeables == null) {
            return;
        }
        for (Closeable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}

